import json

import re
from django import http
from django.contrib.auth import login
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User, Address
import logging

from apps.users.utils import generic_verify_email_url, check_verify_email_token
from utils.response_code import RETCODE
from utils.views import LoginRequiredJSONMixin

logger = logging.getLogger('django')



class RegisterView(View):
    """用户注册"""


    def get(self, request):


        return render(request, 'register.html')


    def post(self,request):

        data = request.POST

        username = data.get('username')
        password = data.get('password')
        password2 = data.get('password2')
        mobile = data.get('mobile')
        allow = data.get('allow')
        sms_code_client = data.get('sms_code')

        if not all([username,password,password2,mobile,allow,sms_code_client]):



            return http.HttpResponseBadRequest('参数不全')


        if not re.match(r'^[0-9a-zA-Z_-]{5,20}$',username):


            return http.HttpResponseBadRequest('用户名不对')

        if not re.match(r'^[0-9a-zA-Z_-]{8,20}$', password):
            return http.HttpResponseBadRequest('密码格式不对')

        if password2 != password:
            return http.HttpResponseBadRequest('两次输入密码不一致')

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('手机号格式不正确')

        if allow != 'on':
            return http.HttpResponseBadRequest('您未同意协议')

        redis_conn = get_redis_connection('code')

        sms_code_server = redis_conn.get('sms_%s'%mobile)
        if not sms_code_server:
            return http.HttpResponseBadRequest('短信验证码已过期')
        if sms_code_server.decode() != sms_code_client:
            return http.HttpResponseBadRequest('短信验证码不一致')




        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                mobile=mobile

            )

        except Exception as e:
            logger.error(e)
            return render(request,'register.html',content_type={'register_errmsg':'创建用户失败'})

        from django.contrib.auth import login
        login(request,user)

        return redirect(reverse('contents:index'))
        # return http.HttpResponseBadRequest('ok')
class RegisterUsernameCountView(View):

    def get(self,request,username):

        count = User.objects.filter(username=username).count()

        return http.JsonResponse({'count':count})

class RegisterMobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        return http.JsonResponse({'count': count})

class LoginView(View):

    def get(self, request):


        return render(request, 'login.html')







    def post(self, request):

        data = request.POST

        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')


        if not all([username, password]):
            return http.HttpResponseBadRequest('参数不全')

        if not re.match(r'^[0-9a-zA-Z_-]{5,20}$', username):
            return http.HttpResponseBadRequest('用户名不对')

        if not re.match(r'^[0-9a-zA-Z_-]{8,20}$', password):
            return http.HttpResponseBadRequest('密码格式不对')

        from django.contrib.auth import authenticate

        user = authenticate(username=username,password=password)

        if user is None:
            return render(request,'login.html',{'login_error_message':'用户名或密码错误'})

        login(request,user)

        if remembered != 'on':
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)

        next = request.GET.get('next')

        if next:
            response = redirect(next)

        else:
            response = redirect(reverse('contents:index'))



        if remembered != 'on':
            response.set_cookie('username',user.username,max_age=None)

        else:
            response.set_cookie('username', user.username, max_age=14*24*3600)

        return response


from django.contrib.auth import logout

class LogoutView(View):

    def get(self,request):
        logout(request)

        response = redirect(reverse('contents:index'))
        response.delete_cookie('username')
        return response

from django.contrib.auth.mixins import LoginRequiredMixin
class UserInfoview(LoginRequiredMixin,View):
    def get(self,request):

        context = {
            'username':request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active,
        }



        return render(request,'user_center_info.html',context=context)


class EmailView(LoginRequiredJSONMixin,View):
    def put(self,request):
        # data = request.POST
        # email = data.get('email')
        #
        body =request.body
        body_str = body.decode()
        data = json.loads(body_str)
        email = data.get('email')


        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code':RETCODE.PARAMERR,'errmsg':'参数错误'})

        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':RETCODE.PARAMERR,'errmsg':'更新错误'})

        from django.core.mail import send_mail
        subject = '美多商城'
        message = ''
        from_email = '美多商城<miss_zhr@126.com>'
        recipient_list = [email]

        verify_url = generic_verify_email_url(request.user.id)
        html_message =  '<p>尊敬的用户您好！</p>' \
                   '<p>感谢您使用美多商城。</p>' \
                   '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                   '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)


        # send_mail(
        #     subject=subject,
        #     message=message,
        #     from_email=from_email,
        #     recipient_list=recipient_list,
        #     html_message=html_message
        # )
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(
            subject=subject,
            message=message,
            from_email=from_email,
            recipient_list=recipient_list,
            html_message=html_message

        )

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})


class EmailVerifyView(View):
    def get(self,request):

        token = request.GET.get('token')
        if token is None:
            return http.HttpResponseBadRequest('参数错误')
        user_id = check_verify_email_token(token)
        if user_id is None:
            return http.HttpResponseBadRequest('参数错误')

        try:
            user = User.objects.get(pk=user_id)
            if user is None:
                user.email_active = True
                user.save()


        except User.DoesNotExist:
            return http.HttpResponseBadRequest('参数错误')


        return redirect(reverse('users:info'))


class AddressView(LoginRequiredMixin,View):
    def get(self,request):
        addresses = Address.objects.filter(user=request.user, is_deleted=False)
        addresses_list =[]
        for address in addresses:
            addresses_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "province_id": address.province_id,
                "city": address.city.name,
                "city_id": address.city_id,
                "district": address.district.name,
                "district_id": address.district_id,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email

            })
        context = {

            'addresses':addresses_list,
            'default_address_id':request.user.default_address_id
        }



        return render(request,'user_center_site.html',context=context)



class CreateAddressView(View):

    def post(self,request):

        count = Address.objects.filter(user=request.user,is_deleted=False).count()
        if count > 20:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})

        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseBadRequest('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseBadRequest('参数email有误')

        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )


            if not request.user.default_address:
                request.user.default_address=address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '数据库操作失败'})
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'address': address_dict})

class UpdateAddressView(LoginRequiredJSONMixin, View):
    def put(self,request,address_id):
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseBadRequest('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseBadRequest('参数email有误')

                # 判断地址是否存在,并更新地址信息
        try:

            Address.objects.filter(pk=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址失败'})
        address = Address.objects.get(pk=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除地址"""
        try:

            address = Address.objects.get(id=address_id)


            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除地址成功'})


class DefaultAddressView(LoginRequiredJSONMixin, View):


    def put(self, request, address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功'})

class ChangePasswordView(LoginRequiredMixin, View):


    def get(self, request, ):



        return render(request, 'user_center_pass.html',)


    def post(self, request):

        # 1.接收参数
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        new_password2 = request.POST.get('new_password2')
        # 2.验证参数
        if not all([old_password, new_password, new_password2]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.HttpResponseBadRequest('密码最少8位，最长20位')
        if new_password != new_password2:
            return http.HttpResponseBadRequest('两次输入的密码不一致')

        # 3.检验旧密码是否正确
        if not request.user.check_password(old_password):
            return render(request, 'user_center_pass.html', {'origin_password_errmsg': '原始密码错误'})
        # 4.更新新密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return render(request, 'user_center_pass.html', {'change_password_errmsg': '修改密码失败'})
        # 5.退出登陆,删除登陆信息
        logout(request)
        # 6.跳转到登陆页面
        response = redirect(reverse('users:login'))

        response.delete_cookie('username')

        return response

# Create your views here.

